package cn.fivestars.springcloud.order.lb;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义负载均衡算法
 *
 * @author liangchenzhou1024@163.com
 * @date 2021/2/4
 */
@Component
@Slf4j
public class MyLoadBalancer implements LoadBalancer {
    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    protected final int getAndIncrement() {
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = (current == 127 ? 0 : current + 1);
        } while (!this.atomicInteger.compareAndSet(current, next));
        log.info("访问次数:next={}", next);
        return next;
    }

    @Override
    public ServiceInstance getInstance(List<ServiceInstance> serviceInstanceList) {

        int index = getAndIncrement() % serviceInstanceList.size();
        ServiceInstance server = serviceInstanceList.get(index);
        return server;
    }
}
